#coding:utf8
import os
import urllib2
import json
import cPickle as pickle
from time import time as now

import MySQLdb
import comm

class Ch2rDb:
    def __init__(self):
        self.conn = None
        self.cur = None
        self.patterns = (now(), None)
        self.sentences = (now(), None)
        if comm.is_dev_env():
            self.host = 'localhost'
            self.user = 'root'
            self.pwd = '321123'
            self.port = 3306
            self.name = 'ch2r'
        else:
            import sae
            self.name = sae.const.MYSQL_DB
            self.user = sae.const.MYSQL_USER
            self.pwd = sae.const.MYSQL_PASS
            self.port = int(sae.const.MYSQL_PORT)
            self.host = sae.const.MYSQL_HOST

    def _get_cur(self):
        if self.cur:
            self.cur.close()
        if self.conn:
            self.conn.close()
        self.conn = MySQLdb.connect(host=self.host, port=self.port, user=self.user, 
                passwd=self.pwd, db=self.name, charset='utf8')
        self.cur = self.conn.cursor()
        return self.cur

    def load_patterns(self):
        if now() < self.patterns[0]:
            return self.patterns[1]
        cur = self._get_cur()
        cur.execute('select interrog_type, interrog_word_type, interrog_words, syntax_sequence from ch2r_sentencepattern;')
        res = []
        for pattern in cur.fetchall():
            pattern = list(pattern)
            pattern[2] = pattern[2].split(u'/')
            pattern[3] = pattern[3].split(u'+')
            res.append(pattern)
        self.patterns = (now()+180, res)
        return self.patterns[1]

    def get_sentence_data(self):
        cur = self._get_cur()
        exts = {}
        cur.execute('select sentence, compressed_sentence, pattern_id from ch2r_extendsentence;')
        for row in cur.fetchall():
            pid = int(row[2])
            if pid not in exts:
                exts[pid] = []
            exts[pid].append((row[0], row[1]))
        cur.close()
        self.cur = cur = self.conn.cursor()
        res = []
        cur.execute('select id, sample, compressed_sample from ch2r_sentencepattern;')
        for row in cur.fetchall():
            id = int(row[0])
            res.append(((row[1], row[2]), exts[id]))
        return res

class OnlineDb:
    def __init__(self):
        self.raw_patterns = None
        self.raw_sentences = None

    def load_patterns(self):
        if not self.raw_patterns:
            if os.access('patterns.cache', os.R_OK):
                data = pickle.load(file('patterns.cache'))
                if data[0] > now():
                    self.raw_patterns = data[1]
                    return self.raw_patterns
            url = 'http://sleepingforest.sinaapp.com/ch2r/data/patterns'
            #url = 'http://127.0.0.1:8080/ch2r/data/patterns'
            resp = urllib2.urlopen(url, '').read()
            self.raw_patterns = json.loads(resp)
            pickle.dump((now()+24*3600, self.raw_patterns), file('patterns.cache', 'w'))
        return self.raw_patterns

    def get_sentence_data(self):
        if not self.raw_sentences:
            if os.access('sentences.cache', os.R_OK):
                data = pickle.load(file('sentences.cache'))
                if data[0] > now():
                    self.raw_sentences = data[1]
                    return self.raw_sentences
            url = 'http://sleepingforest.sinaapp.com/ch2r/data/sentences'
            #url = 'http://127.0.0.1:8080/ch2r/data/sentences'
            resp = urllib2.urlopen(url, '').read()
            self.raw_sentences = json.loads(resp)
            pickle.dump((now()+24*3600, self.raw_sentences), file('sentences.cache', 'w'))
        return self.raw_sentences


if comm.is_dev_env():
    ch2rdb = OnlineDb()
else:
    ch2rdb = Ch2rDb()

del Ch2rDb

rules = [
        #NP: [DP, DNP, NP] -> NP: []
        ('r1', 
         {'NP': [{'DP|1': ['DT']}, 'DNP', {'NP|2': ['NN']}]},
         {'NP': ['DP|1', 'NP|2']}),

        ('r1.1', 
         {'NP': [{'DP|1': ['DT']}, 'DNP', 'DNP', {'NP|2': ['NN']}]},
         {'NP': ['DP|1', 'NP|2']}),

        ('r2', 
         {'NP': ['DNP', 'NP|1']},
         {'NP': ['NP|1']}),

        ('r3', 
         {'NP': ['DP|1', 'ADJP', 'NP|2']},
         {'NP': ['DP|1', 'NP|2']}),

        ('r4', 
         {'VP': ['PP', 'VP|1']},
         {'VP': ['VP|1']}),

        ('r5', 
         {'VP': ['VA|1', 'QP']},
         {'VP': ['VA|1']}),

        #不能去掉ADVP的子树，因为会把有没有的没字去掉
        ('r6', 
         {'VP': ['ADVP', {'VP|1': ['VA']}]},
         {'VP': ['VP|1']}),

        ('r7', 
         {'NP': ['NN', 'NN|1']},
         {'NP': ['NN|1']}), 
        
        ('r8', 
         {'VP': ['ADVP', {'VP|1': ['VV', 'VP']}]},
         {'VP': ['VP|1']}),

#        ('r9', 
#         {'VP': ['VV', {'VP|1': ['VV', 'NP']}]},
#         {'VP': ['VP|1']}),

        ('r10', 
         {'CP': [{'IP|1': ['NP|1', {'VP': ['ADVP', 'VP']}]}, 'DEC']},
         {'NP': ['NP|1']}),

        ('r10.1', 
         {'CP': [{'IP|1': ['NP', 'VP']}, 'DEC']},
         {'CP': ['IP|1']}),

        ('r11',
         {'QP': ['CD', 'CC', 'CD|1']},
         {'QP': ['CD|1']}),

        #索爱的好 -》 好
#        ('r12',
#         {'VP': ['DVP', 'VP|1']},
#         {'VP': ['VP|1']}),

        ('r13-14',
         {'VP': ['VA|1', 'AS']},
         {'VP': ['VA|1']}),

        #有性价比比较高的手机没有？
        ('r15',
         {'NP': [{'CP': ['IP', 'DEC']}, 'NP|1']},
         {'NP': ['NP|1']}),

        #('r15.1',
        # {'VP': ['ADVP|1', {'VP': ['VE|2', 'IP']}]},
        # {'VP': ['ADVP|1', {'VP': ['VE|2']}]}),

        ('r16', 
         {'VP': ['VA|1', 'CLP']},
         {'VP': ['VA|1']}),

        ('r17',
         {'VP': ['PP', 'ADVP', 'VP|1']},
         {'VP': ['VP|1']}),

        ('r18',
         {'NP': [{'NP': ['DP', 'NP']}, 'NP|1']},
         {'NP': ['NP|1']}),

        #三星出了吗，了吗
        ('r19',
         {'VP': ['VV|1', 'AS']},
         {'VP': ['VV|1']}),

        #('r20',
        # {'IP': [{'NP': ['DP', 'NP']}, 'VP|1']},
        # {'IP': ['VP|1']}),


        ('r21',
         {'VP': ['NP|1', 'ADVP', 'VP|2']},
         {'VP': ['NP|1', 'VP|2']}),

        #是大一点好看还是小一点？
        ('r22',
         {'NP': ['ADJP|1', 'QP', 'NP|2']},
         {'NP': ['ADJP|1', 'NP|2']}),

        ('r22.1',
         {'QP': ['ADJP|1', 'QP']},
         {'QP': ['ADJP|1']}),

        ##这台手机 和 这手机哪种颜色更好看？哪种颜色冲突
        #('r23',
        #        {'NP': [{'DP': ['DT', {'CLP': 'M'}]}, 'NP|1']},
        # {'NP': ['NP|1']}),

        #3g通话-》通话
        ('r23',
         {'NP': ['QP', 'NP|1']},
         {'NP': ['NP|1']}),

        ##还有其他的款式，还有-》有,
        #暂时去掉，对怎么xx、什么xx的句子有影响 4.13
        #('r24', 
        # {'VP': ['ADVP', {'VP|1': ['VV', 'NP']}]},
        # {'VP': ['VP|1']}),

        #屏幕大-》大
        ('r25',
         {'VP': [{'NP': ['NN']}, {'VP|1': ['VA']}]},
         {'VP': ['VP|1']}),

        #大一点 -》 大
        ('r26',
         {'VP': ['VA|1', 'ADVP']},
         {'VP': ['VA|1']}),

        #容易坏 -》 坏
        ('r27',
         {'VCD': ['VA', 'VA|1']},
         {'VCD': ['VA|1']}),
]

def standar_rule(rule):
    res = str(rule)
    res = res.replace('[', '(')
    res = res.replace('{', '(')
    res = res.replace(']', ')')
    res = res.replace('}', ')')
    res = res.replace(':', '')
    return res.replace(' ', '')

def standar_str(num, rule):
    return 'r%d'%num + '\t' + standar_rule(rule[1]) + ' -> ' +  standar_rule(rule[2])

def pattern2table(pattern):
    pattern = list(pattern)
    del pattern[1]
    pattern[2] = '/'.join(pattern[2])
    pattern[3] = '+'.join(pattern[3])
    return '\t'.join(pattern)

if __name__ == '__main__':
#    import json
#    patterns.sort(key=lambda x: x[4])
#    for pattern in patterns:
#        pattern = (pattern[0], pattern[4])
#        print json.dumps(pattern, ensure_ascii=False)
#    for i, rule in enumerate(rules):
#        print standar_str(i+1, rule)
    data = ch2rdb.get_sentence_data()
    print data[0]
